package com.gjx.leetcode;

import java.util.ArrayList;
import java.util.List;

//113. 路径总和 II
//
//给定一个二叉树和一个目标和，找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
//
//说明: 叶子节点是指没有子节点的节点。
//
//示例:
//给定如下二叉树，以及目标和 sum = 22，
//
//              5
//             / \
//            4   8
//           /   / \
//          11  13  4
//         /  \    / \
//        7    2  5   1
//返回:
//
//[
//   [5,4,11,2],
//   [5,8,4,5]
//]

public class Solution113 {
	public List<List<Integer>> pathSum(TreeNode root, int sum) {
		List<List<Integer>> res = new ArrayList<>();
		if (root == null) {
			return res;
		}
		helper(root, sum, res, new ArrayList<>());
		return res;
	}
	
	
	private void helper(TreeNode root, int sum, List<List<Integer>> res, List<Integer> path) {
		
		if (root == null) {
			return;
		}
		
		if (root.left == null && root.right == null) {
			if (root.val == sum) {
				List<Integer> list = new ArrayList<>(path);
				list.add(sum);
				res.add(list);
			} 
		} else {
			path.add(root.val);
			helper(root.left, sum - root.val, res, path);
			helper(root.right, sum - root.val, res, path);
			path.remove(path.size()-1);
		}
	}
	
	
	public static void main(String[] args) {
		
		TreeNode root = new TreeNode(5);
		root.left = new TreeNode(4);
		root.right = new TreeNode(8);
		root.left.left = new TreeNode(11);
		root.right.left = new TreeNode(13);
		root.right.right = new TreeNode(4);
		root.left.left.left = new TreeNode(7);
		root.left.left.right = new TreeNode(2);
		
		new Solution113().pathSum(root, 22);
	}
	
}
